#!/bin/bash
#THIS DRIVER WRITTEN BY MATTHEW VONA ARB FOR CARBLogger Network Diagnostics
#WRITTEN USING the DELL T610 PLATFORM
#FOR QUESTIONS WRITE mailto:mvona@arb.ca.gov
#UPDATE: 8/28/2009; Added data file lock handler; Corrected 
#-------------------------------------------------------------
# THIS IS THE FUNCTION CALLED IN THE EVENT THAT CTRL+C IS PRESSED
cleanup()
{
	echo "Caught Signal ... cleaning up."
	if !(rm -f Data/.locked > /dev/null); then
	{
		exit 1
	}
	fi
	echo "Done cleanup ... quitting."
	exit 1
}
DIR="$( cd -P "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
#NETWORK DETECTION STUFF
PATH="/sbin:/usr/sbin:/bin:/usr/bin"
export PATH

function howami {
	wait $! 
	#echo -e "------------------------------------------------"	
	#echo -e "UPTIME:\r"
	up_tim=`uptime | awk '{ print $3 }'` 
	wait $!
	#echo -e "------------------------------------------------"	
	#echo -e "DISK_USAGE:\r"
	rt_dsk_usg=`df -h | awk 'NR==2 { print $5 }' | tr -d '%'`
	hm_dsk_usg=`df -h | awk 'NR==6 { print $5 }' | tr -d '%'`
	wait $!
	#echo -e "------------------------------------------------"	
	#echo -e "BLOCKED ATTEMPTS:\r"	
	blk_atmpt=`dmesg | grep BLOCK | wc -l`
	wait $!
	#echo -e "------------------------------------------------"	
	#echo -e "LAST CARBLogger RESTART:\r"
	clog_strt=`tail -n 2 /home/aqdms/CARBLog/Data/*.log`
	wait $!
	#echo -e "------------------------------------------------"	
	#echo -e "CARBLogger Data Directory Size:\r"
	ddir=`du -h /home/aqdms/CARBLog/Data`	
	wait $!
	
}
function pinger {
    PING=$(ping -c1 -n $1 2>/dev/null)
    if [ "$?" -ne "0" ]; then
	RT='9999'		        
			return 1
    fi

    RT=$( echo $PING | sed 's/.*time\=\([0-9.]* \).*/\1/')
    #echo -e "\tResponded to ping in $RT"
    return 0
}

function is_link_up() {
	local _interface=$1
	[[ -z "$_interface" ]] && return 1
	interface_up=$(ip link show dev $_interface up | grep -F 'LOWER_UP')
	[[ -n "$interface_up" ]] && return 0 || return 1
}

function is_interface_up() {
	local _interface=$1
	[[ -z "$_interface" ]] && return 1
	interface_up=$(ip link show dev $_interface up)
	[[ -n "$interface_up" ]] && return 0 || return 1
}

function is_dhcp_client_running() {
	local _interface=$1
	[[ -z "$_interface" ]] && return 1
	# Check for running dhcp clients
	local dhcp_pid=$(pgrep '^(dhcp|dhclient)')
	# Nothing found?
	[[ -z "$dhcp_pid" ]] && return 1
	# We found something, see if it's for this interface
	# there could be multiple processes too, so loop through
	# whatever we found in $dhcp_pid
	for pid in $dhcp_pid ; do
		grep -qF "$_interface" /proc/$pid/cmdline && return 0
	done
	# If we get here, we haven't found anything so
	# assume we're not using dhcp
	return 1
}


#THE DIAGNOSTIC DATA (DIAG) ROUTINE TAKES THE DATA STREAM FROM THE NET UTILITY
#AND TEST FOR THE RECOGNITION OF KEY WORDS IN EACH LINE OF OUTPUT.
#IF THE KEY WORD IS DETECTED ON THAT LINE, A TEST IS PERFORMED. 
#IF THE TEST SUGGESTS THAT AN ERROR CONDITION EXISTS BASED UPON THE ALLOWABLE
#RANGES SPECIFIED BY THE ARB CHECKSHEET, THE OFFENDING LINE IS WRITTEN OUT 
#TO A FILE IN THE Data DIRECTORY. THE NAME OF THE DESTINATION FILE IS
#errors{HH}. THE FILES CAN THEN BE PARSED AND UTILIZED BY ANY ALERT PROGRAM?DAEMON.
diag()
{
this_name=$(cat ${DIR}/.usr$instance | grep -o "\-r [A-Za-z0-9]*" | awk '{ print $2 }') 
thishour=`date "+%H"`
thisalert="errors$thishour"
while read DIAGS
do
awk -v name=$this_name '

{                                           
# CHECK FOR ANY WARNINGS
if (/WARN/) 
	{ print name " WARNING DETECTED:"$0 }

}' >> "Data/$thisalert"
done
}
#BEGIN WRITE
#THIS FUNCTION HANDELS READ RIGHT HANDSHAKES BETWEEN VARIOUS DRIVERS
#IN GENERAL, THE DATA IS PLACED IN THE VARIABLE $TIMESTAMP PRIOR TO CALL
#NEXT, IT OPENS THE DATA DIRECTORY AND LOOKS FOR THE .locked FILE
#IF IT EXISTS, IT HANGS OUT UNTIL IT DOESN'T EXIST. AT THAT POINT
#IT CREATES A .locked FILE, AND APPENDS TO THE DATA RECORD.
#FINALLY IT REMOVES THE .locked FILE IT HAS CREATED.
#written by MJV
write()
{
#CONFIRM THAT THERE IS NO HIDDEN FILE CALLED '.locked'
	while [ -e "Data/.locked" ];
		do
			sleep .2;
		done	
	echo "LOCKED" > "Data/.locked";
        #PARSE THE .disabled File
        channel_status=`cat ${DIR}/.disabled$instance`
        #IF THE FILE DOSEN'T EXIT OR IS NOT ACCESIBLE
        #MAKES SURE A VALUE OF 0 IS USED
        if [ `expr $channel_status + 0` -eq 1 ]; then
        	if !(echo "$data" | sed 's/^/'$timestamp'/g'|sed 's/$/'\-\-DISABLED\-\-'/g'| tee -a "Data/$datafile" ); then
                	{
                		echo "GENERAL FAILURE WRITING TO RECORD: $#";
                        	cleanup;
                	}
                fi
           else
         	if !(echo "$data" | sed 's/^/'$timestamp'/g'| tee -a "Data/$datafile" | diag); then
			{
				echo "GENERAL FAILURE WRITING TO RECORD: $#";
				cleanup;
			}
		fi
	fi
	if !(rm -f "Data/.locked" > /dev/null); then
		{
			echo "GENERAL FAILURE REMOVING LOCK: $#";
			exit 1;	
		}
	fi
	if !(timestamp="" && data=""); then
		{
		echo "GENERAL FAILURE CLEARING WRITE BUFFER: $#";
		exit 1;
		}
	fi	
}

#THIS IS THE ACTUAL COMMUNICATION WITH THE INSTRUMENT
#THE TIMER CONTROL. AT THE BEGINING IT TESTS FOR THE 
#EXISTENCE IF TOGGLE VARRIABLES WHICH ARE UTILIZED BOTH BY
#THE COMM ROUTINE runit() AND THE DIAGNOSTICS DATA ROUTINE
#diag()
runit()
{
data=''
today=`date "+%Y-%d-%m"`
timestamp=$rprt_nm::`date "+%m-%d-%Y_%H:%M"`:::
#THIS IS THE NAME OF THE DATA FILE RIGHT NOW
datafile="$saroad-$today"
#TALK TO THE INSTRUMENT, PRE-APPEND THE TIMESTAMP AND REPORTING NAME TO EACH
#LINE OF OUTPUT AND tee TO THE DATA FILE, then pass to the diag routine.
howami
data=`echo "root_disk=${rt_dsk_usg}"`
data="${data} home_disk=${hm_dsk_usg}" 
data="${data} block_attempts=${blk_atmpt}" 
data="${data} uptime=${up_tim}" 
pinger google.com
data="${data} ping_resp=${RT}"
pinger 74.125.224.131
data="${data} ip_ping_resp=${RT}"
write
}
#THIS IS THE FUNCTION RUN IN THE EVENT THAT THE REQUIRED PARAMETERS
#ARE NOT ENTERED.
usage()
{
clear
cat << EOF
usage: $0 options
OPTIONS:
-h	display help
-r	rprt_nm [rn]
-s	SAROAD number of the station
-I	instance
Last updated 8/17/2012
EOF
}
#HELP FUNCTION GIVES BACKGROUND ON THIS DRIVER
help_me ()
{
clear
cat .help
exit 0
}
def_opts ()
{
clear
cat .options
}

##CLEAR ALL VARIABLES               
rprt_nm= ; cmnd1= ; wt_rsp1= ; bd_rt= ; rsp_lngth= ; izs_val= ;
dvc_prt= ; frqncy= ; dtr= ; ctr= ; p8n1= ; saroad= ; p8n1= ; id_nmbr= ; 
instance=1 ;
abs_path=`pwd`
##INITIALIZE THE BUFFER
return='NOT WRITTEN TO'
##loop through all variables and parameters
##Note that the position of the colon indicates the presence
##of a parameter to collect. The h parameter simply
##returns the help message.

while getopts “hr:a:s:w:l:t:I:” OPTION
do
	case $OPTION in
		s)
		saroad=$OPTARG
		;;
		r)
		rprt_nm=$OPTARG
		;;
		d)
		dvc_prt=$OPTARG
		;;
		c)
		cmnd1=$OPTARG
		;;
		I)
		instance=$OPTARG
		;;
		h)
		help_me
		exit 1
		;;
		*)
		usage
		exit 1
		;;
	esac
done
#CHECK FOR THE CRITICAL PARAMETERS, IF THEY ARE NOT PRESENT THEN
#RUN THE USAGE FUNCTION WHICH RETURNS THE INSTRUCTIONS FOR PROPER USAGE
#MUST HAVE r n d b c w l s
if [ -z "$rprt_nm" ] || [ -z "$saroad" ] || [ -z "$instance" ]
	then
		{
		usage
		exit
		}
fi
	#INITIALIZED THE RAN VARIABLE. THIS IS USED TO TOGGLE THE TIMER GATE
ran=0
	#TRAP CTRL+C
trap cleanup 1 2 3 6 15
	#SETUP THE OPERATING LOOP
while :
do
	#SET THE SECOND VARIABLE AS THE SECOND VALUE FROM THE DATA STAMP 
second=`date "+%S"`
	#IF THE SECOND VALUE IS LESS THAN 02, BEGIN RUNNING
if [ "$second" -eq "00" ] && [ "$ran" -eq "0" ]; then
	{
		#RUN THE RUNIT FUNCTION
			runit
		#TOGGLE THE RAN VARIABLE SO THAT THE PROCESS WILL NOT REPEAT
		#UNTIL THE BEGINNING OF TH-b9600 -d "/dev/ttyS0" -c "T LIST ALL\\r" -r "API200E" -w4 -l 1500 -p8n1 -s34305 -i offE NEXT MINUTE.
			ran=1
		#WAIT FOR COMPLETION OF THE RUNIT FUNCTION AND THE VARIABLE
		#SET
			sleep 1
	}
	#IF THE SECOND VALUE IS GREATER THAT 02, RESET RAN TO 0
	#AND WAIT ONE SECOND BEFORE CHECKING AGAIN
else 
	{
		#WAIT ONE SECOND
			sleep .5
		#SET RAN TO 0
			ran=0
	}
fi
done;
exit;

